<template>
  <div class="anime-anthology">
    <p>{{ title }}</p>
    <div class="anthologys_box">
      <SelectCard
        :isActive="anthologyActive === index"
        @click="clickEven(item.id, index, item.videoUrl)"
        v-for="(item, index) in VideoSrc"
        :key="item.id"
      >
        <span>第{{ item.episodes }}集</span>
      </SelectCard>
    </div>
  </div>
</template>

<script>
import { inject, ref, watch, onBeforeUnmount } from 'vue'
import { useRoute } from 'vue-router'

import { useVideoPlay } from '@/stores/VideoPlay'
import { toAnimeMain } from '../../router/jump'
import { Storage_ } from '../../class/Storage'

import SelectCard from '../Card/SelectCard.vue'

export default {
  name: 'AnimeAnthology',
  props: {
    title: {
      default: ''
    }
  },
  emits: ['getVideoSrc'],
  components: {
    SelectCard
  },
  setup() {
    const route = useRoute()
    const anthologyActive = ref(route.params.ep - 0 || 0)
    const VideoSrc = inject('VideoSrc')
    const AnimeMsg = inject('AnimeMsg')
    const VideoPlay = useVideoPlay()
    console.log(AnimeMsg)
    console.log(VideoSrc)

    // 选集初始化
    ;(function AnthologyInit() {
      let item = Storage_.getItemSon('anime')

      watch(
        VideoSrc,
        () => {
          if (VideoSrc.value.length <= 0) return
          if (item) {
            item.forEach((item_son) => {
              if (item_son.name + '' === route.params.id + '') {
                item = item_son.value
                clickEven(item.id, item.ep, VideoSrc.value[item.ep].videoUrl)
                return
              } else {
                VideoPlay.playUrl = VideoSrc.value[route.query.ep || 0].videoUrl
              }
            })
          } else {
            VideoPlay.playUrl = VideoSrc.value[route.query.ep || 0].videoUrl
          }
        },
        { immediate: true }
      )
    })()

    function clickEven(id, index, url) {
      anthologyActive.value = index
      VideoPlay.playUrl = url
      toAnimeMain(id, index, 'replace')
    }

    onBeforeUnmount(() => {
      let id = VideoSrc.value[0].animeId
      if (!id) return

      const anime_history = {
        name: id,
        value: {
          id: id,
          ep: anthologyActive.value,
          cover: AnimeMsg.value.cover,
          title: AnimeMsg.value.animeTitle,
          episodes: VideoSrc.value[anthologyActive.value].episodes
        }
      }
      Storage_.setItemSon('anime', anime_history)
    })

    return {
      VideoSrc,
      anthologyActive,
      clickEven
    }
  }
}
</script>

<style lang="scss" scoped>
.anime-anthology {
  p {
    user-select: none;
    color: $font;
    margin-bottom: 20px;
    font-weight: 600;
  }
  .anthologys_box {
    display: flex;
    flex-wrap: wrap;
    gap: 10px 6px;
    span {
      user-select: none;
      // line-height: 32px;
      font-size: 14px;
    }
  }
}
</style>
